package com.alignet.gn.web;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.NDC;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.alignet.gn.hibernate.TgnRole;
import com.alignet.gn.hibernate.TgnUser;
import com.alignet.gn.hibernate.dao.TgnRoleDAO;
import com.alignet.gn.service.RoleService;
import com.alignet.gn.service.UserService;
import com.alignet.gn.service.impl.Constants;
import com.alignet.gn.sesion.Eventos;
import com.alignet.gn.util.GNUtils;
import com.alignet.vpos.logging.MDCParams;

@Scope("session")
@Component("role")
public class RoleBean implements Serializable{

	private static final long serialVersionUID = -6806540982809561427L;
	private static final Logger log = LoggerFactory.getLogger(RoleBean.class);
	private static  org.apache.log4j.Logger logMdc = org.apache.log4j.Logger.getLogger("MDC");
	private String pageResponse;
	private List<TgnRole> rolesD;
	private TgnRole roleD;
	private String name;
	private String cadena;
	private String state;
	public Integer id;
	HtmlDataTable dataTable;
	
	
	
	public HtmlDataTable getDataTable() {
		return dataTable;
	}

	public void setDataTable(HtmlDataTable dataTable) {
		this.dataTable = dataTable;
	}

	@ManagedProperty(value = "#{RolService}")
	private RoleService serviceR;
	
	@ManagedProperty(value = "#{UserService}")
	private UserService serviceU;

	@Autowired
	public void setTransactionBean(RoleService serviceR, UserService serviceU) {
		this.serviceR=serviceR;
		this.serviceU=serviceU;
	}
	
	final transient private  TgnRoleDAO roleDAO;
	
	
	@Autowired
	public RoleBean(TgnRoleDAO roleDAO) {		
		this.roleDAO = roleDAO;
	}
	
	public String getPageResponse() {
		return pageResponse;
	}

	public void setPageResponse(String pageResponse) {
		this.pageResponse = pageResponse;
	}
	
	
	public String getCadena() {
		return cadena;
	}

	public void setCadena(String cadena) {
		this.cadena = cadena;
	}

	///ACTION
	public String processAction() {
		return pageResponse;
	}
	
	public void updateRole(ActionEvent event){
		FacesContext fc = FacesContext.getCurrentInstance();
		log.debug("[ newRole ]");
		pageResponse=Constants.PAGE_ROLEDETAIL;
		
		StringBuffer buf = new StringBuffer();

		String[] completa = cadena.split(",");
		for (int i = 0; i < completa.length; i++) {
			buf.append(",{'ID':'" + completa[i] + "'}");
		}
		String actionxedit = buf.toString();
		actionxedit = "[" + actionxedit.substring(1) + "]";
		
		TgnRole role = roleDAO.findById(id);
		role.setVcName(name);
		role.setChState(state);
		if(GNUtils.esVacioNulo(name)){
			fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, GNUtils.getMessage("Requser1"), null));
			fc.renderResponse();
		}else{
			String rpta=serviceR.updateRole(role,cadena,actionxedit);
			if(rpta.equals("success")){
				fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Los datos se actualizaron satisfactoriamente", null));
				fc.renderResponse();
			}else{
				fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, GNUtils.getMessage(rpta), null));
				fc.renderResponse();
			}
		}
		
	}
	
	public void registerRole(ActionEvent event){
		log.debug("[ newRole ]");
		pageResponse=Constants.PAGE_ROLESEARCH;
		FacesContext fc = FacesContext.getCurrentInstance();
		
		StringBuffer buf = new StringBuffer();

		String[] completa = cadena.split(",");
		for (int i = 0; i < completa.length; i++) {
			buf.append(",{'ID':'" + completa[i] + "'}");
		}
		String actionxedit = buf.toString();
		actionxedit = "[" + actionxedit.substring(1) + "]";
		
		TgnRole role = new TgnRole();
		role.setVcTypeentity("3");
		role.setVcName(name);
		
		String rpta=serviceR.registerRole(role,cadena,actionxedit);
		if(rpta.equals("success")){
			pageResponse=Constants.PAGE_ROLESEARCH;
			fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Los datos se actualizaron satisfactoriamente", null));
			fc.renderResponse();
		}else{
			pageResponse=Constants.PAGE_ROLENEW;
			fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, GNUtils.getMessage(rpta), null));
			fc.renderResponse();
		}
	}

	
	
	
	public void processDetail(ActionEvent event){
		NDC.push("RoleBean - processDetail");
		pageResponse =Constants.PAGE_ROLEDETAIL;
		HttpServletRequest req= ( HttpServletRequest ) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		Eventos ev= new Eventos();
		try {
			//Eventos
			ev.setEnmascarado(MDCParams.CLRPAN_NOT_SHOWN);
			ev.setAccion("Detalle de Rol");
			roleD = (TgnRole) dataTable.getRowData();
			id=roleD.getInIdrole();
			name=roleD.getVcName();
			state=roleD.getChState();

			serviceR.obtieneRol(roleD);
			
			ev.setEstado(MDCParams.STATUS_SUCCESSFUL);			
		} catch (RuntimeException re) {
			System.out.println("process failed "+ re);
			ev.setEstado(MDCParams.STATUS_FAIL);
			ev.setDescripcion("Error de aplicacion");
		} catch (Exception re) {
			System.out.println("process failed "+ re);
			ev.setEstado(MDCParams.STATUS_FAIL);
			ev.setDescripcion("Error de aplicacion");
		} catch (Error re) {
			System.out.println("process failed "+ re);
			ev.setEstado(MDCParams.STATUS_FAIL);
			ev.setDescripcion("Error de aplicacion");
		}
		NDC.pop();
		req.setAttribute("eventos", ev);
	}
	
	public void newRole(ActionEvent event){
		log.debug("[ newRole ]");
		name="";
		state="";
		pageResponse=Constants.PAGE_ROLENEW;
		serviceR.newRole();
	}
	
	public void procesMenuQuery(ActionEvent event) {
		log.debug("[ procesMenuQuery ]");
		dataTable = new HtmlDataTable();
		generate();
		pageResponse = Constants.PAGE_ROLESEARCH;
		HttpServletRequest req= ( HttpServletRequest ) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		Eventos ev= new Eventos();
		ev.setEnmascarado(MDCParams.CLRPAN_NOT_SHOWN);
		ev.setAccion("Pagina de listado de Roles");
		ev.setEstado(MDCParams.STATUS_SUCCESSFUL);
		req.setAttribute("eventos", ev);
	}
	
	private void generate() {
		
	  	try {
	  		final TgnUser us=serviceU.findUser();;
	  		int numEvents = ((Long)(roleDAO.findByQuery("select count(id) from TgnRole as model where not model.chState='3' and not model.inIdrole="+us.getTgnRole().getInIdrole()).get(0))).intValue();
	  		//int numEvents = ((Long)(dao.findByQuery("select count(id) from TgnTransaction  ").get(0))).intValue();
			log.debug("COUNT numEvents = "+numEvents);
			
			DetachedCriteria criteria = DetachedCriteria.forClass(TgnRole.class)
				     .add( Property.forName("vcTypeentity").eq("3") )
				     //.add( Property.forName("inIdentity").eq(idCommerce) )
				     .add( Property.forName("inIdrole").ne(us.getTgnRole().getInIdrole()) )
				      .add( Property.forName("chState").ne("2") )
				     .addOrder(Order.desc("dtRegistry"));
			
			rolesD =roleDAO.findByCriteria(criteria);


		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
	
	public void process(ActionEvent event) {
		
	}
	
	public List<TgnRole> getRolesD() {
		return rolesD;
	}

	public void setRolesD(List<TgnRole> rolesD) {
		this.rolesD = rolesD;
	}

	public TgnRole getRoleD() {
		return roleD;
	}

	public void setRoleD(TgnRole roleD) {
		this.roleD = roleD;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}
	

	public void deleteRole(ActionEvent event){
		FacesContext fc = FacesContext.getCurrentInstance();
 		log.debug("[ deleteRole ]");
		pageResponse=Constants.PAGE_ROLESEARCH;
		TgnRole role = roleDAO.findById(id);
		role.setChState("2");
		serviceR.delete(role);
		log.info("Datos actualizados");
		fc.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "El rol fue eliminado satisfactoriamente", null));
		fc.renderResponse();
	}

}